package com.iot.ammeter.network.mock

import com.iot.ammeter.model.parcelable.*
import com.iot.ammeter.network.services.BaseDataService
import com.iot.ammeter.network.MockResponse
import com.iot.ammeter.network.ResponseWrap
import retrofit2.Call
import retrofit2.mock.BehaviorDelegate
import java.util.*
import kotlin.random.Random


/**
 * [BaseDataService] API 接口的 mock 实现
 */
class BaseDataMock(private val delegate: BehaviorDelegate<BaseDataService>) : BaseDataService,
    MockResponse {

    private val deviceInfoMockData = LinkedList<DeviceInfo>()
    private val userInfoMockData = LinkedList<UserInfo>()
    private val lastMonthInfoMockData = LinkedList<LastMonthInfo>()

    private val location = Location("东莞理工学院城市学院", "东莞校区", "学生宿舍8号楼A栋", "330")

    init {
        deviceInfoMockData.add(DeviceInfo("0", 12F, 102F, DeviceStatus.ONLINE, location))
        deviceInfoMockData.add(DeviceInfo("1", 20F, 132F, DeviceStatus.OFFLINE, location))
        deviceInfoMockData.add(DeviceInfo("2", 15F, 190F, DeviceStatus.ARREARAGE, location))
        deviceInfoMockData.add(DeviceInfo("3", 32F, 211F, DeviceStatus.ELECTRIC_ERROR, location))

        repeat(5) {
            userInfoMockData.add(
                UserInfo(
                    it.toString(),
                    if (it < 4) it.toString() else null,
                    Random.nextDouble(60.0, 150.0).toFloat(),
                    Random.nextBoolean()
                )
            )
        }

        repeat(2) {
            lastMonthInfoMockData.add(
                LastMonthInfo(
                    LastMonthCharge(Random.nextDouble(80.0, 150.0).toFloat(), Random.nextBoolean()),
                    LastMonthMeter(
                        Random.nextDouble(400.0, 550.0).toFloat(),
                        Random.nextDouble(650.0, 800.0).toFloat()
                    )
                )
            )
        }
    }

    override fun getDeviceInfo(deviceId: String): Call<ResponseWrap<DeviceInfo>> {
        var deviceInfo: DeviceInfo? = null
        deviceInfoMockData.forEach {
            if (it.deviceId == deviceId) {
                deviceInfo = it
                return@forEach
            }
        }
        return delegate.returningResponse(deviceInfo!!.asResponse()).getDeviceInfo(deviceId)
    }

    override fun getUserInfo(token: String): Call<ResponseWrap<UserInfo>> {
        val userInfo = userInfoMockData.random()
        return delegate.returningResponse(userInfo.asResponse()).getUserInfo(token)
    }

    override fun getLastMonthInfo(
        userId: String,
        deviceId: String?
    ): Call<ResponseWrap<LastMonthInfo>> {
        val lastMonthInfo = lastMonthInfoMockData.random()
        return delegate.returningResponse(lastMonthInfo.asResponse())
            .getLastMonthInfo(userId, deviceId)
    }
}


